import { createWebHashHistory, createRouter } from 'vue-router'
import * as common from '../utils/common'
import store from '../state/index'
//配置路由规则：配置组件的访问路径
const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: '/:catchAll(.*)',
    component: () => import('../view/error/404.vue'),
    name: 'NotFound'
  },
  {
    path: "/login",
    component: () => import('../view/Login.vue')
  },
]

//创建路由实例
let router = createRouter({
  routes: routes, //注册路由规则
  history: createWebHashHistory()  //路由方式 createWebHistory() 或 createWebHashHistory()
})

/**
 * 初始路由信息
 */
function initRouter() {
  let appendRoute = {};
  appendRoute.path = "/layout";
  appendRoute.name = "layout";
  appendRoute.component = () => import(`../view/layout/Layout.vue`);
  appendRoute.children = [];
  //从store获取当前的权限信息
  let menus = store.getters.menus;

  // 首先把你需要动态路由的组件地址全部获取
  let modules = import.meta.glob('../view/**/*.vue')

  for (let menu of menus) {
    // console.log(menu)
    menu.children.forEach((temp, index) => {
      let item = {};
      //将从store中获取的路由路径对应组件名称 /nodelist/approveNode
      let vueName = temp.path
      let indexN = temp.path.lastIndexOf("/") + 1
      vueName = vueName.substr(0, indexN) + vueName.substring(indexN).charAt(0).toUpperCase() + vueName.substring(indexN + 1)
      // item.component = () => import(`../view${vueName}.vue`);  // ../view/nodelist/ApproveNode
      item.component = modules[`../view${vueName}.vue`]
      item.path = temp.path;
      item.name = temp.title;
      appendRoute.children.push(item);
    });
  }
  //添加菜单外的AddItemToLevel、ServiceBuy、UserToCustomerService路由
  //appendRoute.children.push({path:"/nurse/addItemToLevel",component:() => import('@/views/nurse/AddItemToLevel.vue')})

  router.addRoute(appendRoute);
}

//路由守卫
router.beforeEach((to, from, next) => {

  // // 1. 定义免登录白名单
  // const whiteList = ['/login', '/404']
  // // 2. 检查登录状态
  // const isAuthenticated = common.getSessionStorage("user") !== null

  // // 3. 处理登录页的特殊情况
  // if (to.path === '/login') {
  //   isAuthenticated ? next('/layout') : next()
  //   return
  // }

  // // 4. 非白名单路由检查登录
  // if (!whiteList.includes(to.path)) {
  //   if (!isAuthenticated) {
  //     next(`/login?redirect=${encodeURIComponent(to.fullPath)}`)
  //     return
  //   }
  // }

  let currentPath = to.fullPath;
  let menuArray = store.getters.menus;
  //第一次访问登录页面时，并没有菜单列表，此时也动态加载了路由并让length变成了3，导致登录后不会再执行初始化加载路由,加上其他额外条件
  if (router.getRoutes().length == 3 && menuArray != null && menuArray.length > 0 && menuArray != 'undefined') {

    //需要动态加载路由信息
    initRouter();
    next({ path: to.path });
    return;
  }
  let menus = store.getters.menus;
  let currentMenu = null;

  let firstLevelSize = menus.length;
  let secondLevelSize = 0;

  for (let i = 0; i < firstLevelSize && currentMenu == null; i++) {
    secondLevelSize = menus[i].children.length;
    for (let j = 0; j < secondLevelSize; j++) {
      //说明找到了
      if (menus[i].children[j].path == currentPath) {
        currentMenu = menus[i].children[j];
        break;
      }
    }
  }

  if (currentMenu) {
    //调用vuex判断是否需要添加到state的tabs中
    store.commit("addTab", currentMenu);
  }
  //放行

  // 根据用户角色或其他条件更新菜单
  // if (common.getSessionStorage("user") != null) {
  //   const userRole = common.getSessionStorage("user"); // 假设用户角色存储在 localStorage 中
  //   console.log(userRole);
  //   if (userRole) {
  //     store.dispatch('updateMenusByCondition', userRole);
  //   }
  // }


  next();
});


export default router